/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package sys.donto.telas;

import java.security.Principal;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import sys.donto.atestado.Atestado;
import sys.donto.atestado.AtestadoDAO;
import sys.donto.dentista.Dentista;
import sys.donto.dentista.DentistaDAO;
import sys.donto.dentista.DentistaTableModel;
import sys.donto.paciente.Paciente;
import sys.donto.paciente.PacienteDAO;
import sys.donto.paciente.PacienteTableModel;
import sys.donto.util.ConnectionFactory;
import sys.donto.util.Util;

/**
 *
 * @author JOABB
 */
public class telaAtestados extends javax.swing.JDialog {
    private Atestado atestado;

    /**
     * Creates new form telaAtestados
     */
    public telaAtestados() {
        initComponents();
        setModal(true);
        setLocationRelativeTo(null);
        limpaCampos();
        
        setTitle("sysDONTO - Atestado");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        tfPaciente = new javax.swing.JTextField();
        tfDentista = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        btPesquisarPaciente1 = new javax.swing.JButton();
        btNovoPaciente1 = new javax.swing.JButton();
        btNovoDentista1 = new javax.swing.JButton();
        btPesquisarDentista1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        tfData = new javax.swing.JFormattedTextField();
        jLabel13 = new javax.swing.JLabel();
        tfDiasdeAtestado = new javax.swing.JTextField();
        btGerarAtestado = new javax.swing.JButton();
        btSair = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setLayout(null);

        tfPaciente.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        tfPaciente.setEnabled(false);
        tfPaciente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfPacienteActionPerformed(evt);
            }
        });
        jPanel1.add(tfPaciente);
        tfPaciente.setBounds(110, 170, 506, 20);

        tfDentista.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        tfDentista.setEnabled(false);
        tfDentista.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfDentistaActionPerformed(evt);
            }
        });
        jPanel1.add(tfDentista);
        tfDentista.setBounds(110, 200, 506, 20);

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel12.setText("DENTISTA:");
        jPanel1.add(jLabel12);
        jLabel12.setBounds(40, 200, 70, 15);

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel11.setText("PACIENTE:");
        jPanel1.add(jLabel11);
        jLabel11.setBounds(40, 170, 70, 15);

        btPesquisarPaciente1.setBackground(new java.awt.Color(0, 153, 153));
        btPesquisarPaciente1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/Search 16.png"))); // NOI18N
        btPesquisarPaciente1.setToolTipText("Pesquisar");
        btPesquisarPaciente1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarPaciente1ActionPerformed(evt);
            }
        });
        jPanel1.add(btPesquisarPaciente1);
        btPesquisarPaciente1.setBounds(630, 170, 37, 25);

        btNovoPaciente1.setBackground(new java.awt.Color(0, 153, 153));
        btNovoPaciente1.setForeground(new java.awt.Color(0, 153, 153));
        btNovoPaciente1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/add-16.png"))); // NOI18N
        btNovoPaciente1.setToolTipText("Novo");
        btNovoPaciente1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoPaciente1ActionPerformed(evt);
            }
        });
        jPanel1.add(btNovoPaciente1);
        btNovoPaciente1.setBounds(670, 170, 37, 25);

        btNovoDentista1.setBackground(new java.awt.Color(0, 153, 153));
        btNovoDentista1.setForeground(new java.awt.Color(0, 153, 153));
        btNovoDentista1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/add-16.png"))); // NOI18N
        btNovoDentista1.setToolTipText("Novo");
        btNovoDentista1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoDentista1ActionPerformed(evt);
            }
        });
        jPanel1.add(btNovoDentista1);
        btNovoDentista1.setBounds(670, 200, 37, 25);

        btPesquisarDentista1.setBackground(new java.awt.Color(0, 153, 153));
        btPesquisarDentista1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/Search 16.png"))); // NOI18N
        btPesquisarDentista1.setToolTipText("Pesquisar");
        btPesquisarDentista1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarDentista1ActionPerformed(evt);
            }
        });
        jPanel1.add(btPesquisarDentista1);
        btPesquisarDentista1.setBounds(630, 200, 37, 25);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("ATESTADO");
        jLabel3.setFocusable(false);
        jPanel1.add(jLabel3);
        jLabel3.setBounds(210, 40, 360, 40);

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel10.setText("Quant. dias de atestado:");
        jPanel1.add(jLabel10);
        jLabel10.setBounds(210, 140, 170, 15);

        tfData.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        try {
            tfData.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        tfData.setEnabled(false);
        jPanel1.add(tfData);
        tfData.setBounds(110, 140, 76, 20);

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel13.setText("DATA:");
        jPanel1.add(jLabel13);
        jLabel13.setBounds(60, 140, 50, 15);

        tfDiasdeAtestado.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel1.add(tfDiasdeAtestado);
        tfDiasdeAtestado.setBounds(370, 140, 59, 20);

        btGerarAtestado.setBackground(new java.awt.Color(0, 153, 153));
        btGerarAtestado.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btGerarAtestado.setForeground(new java.awt.Color(255, 255, 255));
        btGerarAtestado.setMnemonic('G');
        btGerarAtestado.setText("GERAR");
        btGerarAtestado.setToolTipText("Gerar");
        btGerarAtestado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGerarAtestadoActionPerformed(evt);
            }
        });
        jPanel1.add(btGerarAtestado);
        btGerarAtestado.setBounds(460, 250, 75, 30);

        btSair.setBackground(new java.awt.Color(0, 153, 153));
        btSair.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btSair.setForeground(new java.awt.Color(255, 255, 255));
        btSair.setMnemonic('S');
        btSair.setText("SAIR");
        btSair.setToolTipText("Sair");
        btSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSairActionPerformed(evt);
            }
        });
        jPanel1.add(btSair);
        btSair.setBounds(540, 250, 70, 30);

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/donto/imagens/telasPP.jpg"))); // NOI18N
        jPanel1.add(jLabel8);
        jLabel8.setBounds(0, 0, 740, 310);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 740, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void limpaCampos(){
        tfData.setText("");
        tfDentista.setText("");
        tfDiasdeAtestado.setText("");
        tfPaciente.setText("");
        atestado=new Atestado();
    }
    
    private void tfPacienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfPacienteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfPacienteActionPerformed

    private void tfDentistaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfDentistaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfDentistaActionPerformed

    private void btPesquisarPaciente1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarPaciente1ActionPerformed
        PacienteDAO dao = new PacienteDAO();
        List<Paciente> lista = dao.listar();
        PacienteTableModel ptm = new PacienteTableModel(lista);
        Object o = telaPesquisa.exibeTela(ptm, "paciente");
        Paciente p;
            
        if (o != null) {
            p = dao.pesquisaId(Integer.valueOf(String.valueOf(o)));
            atestado.setPaciente(p);
            tfPaciente.setText(p.getNome());
        }
    }//GEN-LAST:event_btPesquisarPaciente1ActionPerformed

    private void btNovoPaciente1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoPaciente1ActionPerformed
        telaPaciente tp = new telaPaciente();
        tp.setVisible(true);
    }//GEN-LAST:event_btNovoPaciente1ActionPerformed

    private void btNovoDentista1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoDentista1ActionPerformed
        telaDentista td = new telaDentista();
        td.setVisible(true);// TODO add your handling code here:
    }//GEN-LAST:event_btNovoDentista1ActionPerformed

    private void btPesquisarDentista1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarDentista1ActionPerformed
        DentistaDAO dao = new DentistaDAO();// butão de pesquisa de estado.
        List<Dentista> lista = dao.listar();
       DentistaTableModel dtm = new DentistaTableModel(lista);
        Object o = telaPesquisa.exibeTela(dtm, "dentista");
        Dentista d;
        if (o != null) {
            d = dao.pesquisaId(Integer.valueOf(String.valueOf(o)));
            atestado.setDentista(d);
            tfDentista.setText(d.getNome());
        }
    }//GEN-LAST:event_btPesquisarDentista1ActionPerformed

    private void btSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSairActionPerformed
        dispose();
    }//GEN-LAST:event_btSairActionPerformed

    private void btGerarAtestadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGerarAtestadoActionPerformed
        
        if (Util.chkVazio(tfPaciente.getText(),tfDiasdeAtestado.getText(),
                tfDentista.getText(),tfData.getText())) {
                  
            //METODO NECESSÁRIO PARA SALVAR A DATA NO BANCO DE DADOS
        try {
            if (!tfData.getText().replaceAll("/", "").isEmpty()) {
                
                DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
                java.util.Date data1;
                data1 = new java.util.Date(fmt.parse(tfData.getText()).getTime());
                atestado.setDataAtestado(data1);
            }
        } catch (ParseException ex) {
            Logger.getLogger(telaConsulta.class.getName()).log(Level.SEVERE, null, ex);

        }
        
            atestado.setDiasDeAtestado(tfDiasdeAtestado.getText()); 
            AtestadoDAO dao = new AtestadoDAO();
            dao.salvar(atestado);
           
        }
        //CHAMANDO RELATORIO
        
        JasperReport pathjrxml;
        HashMap parametros = new HashMap();
        String sql = "", texto = "";
            
        Connection connection = new ConnectionFactory().getConnection();
        
        try{
            JDialog viewer = new JDialog(new javax.swing.JFrame(),"Visualização do Relatorio");
            viewer.setSize(1000, 600);
            viewer.setLocationRelativeTo(null);
            viewer.setModal(true);
            pathjrxml = JasperCompileManager.compileReport("src/relatorios/relatorioAtestado.jrxml");
            JasperPrint printReport = JasperFillManager.fillReport(pathjrxml, parametros, connection);
            JasperViewer jv = new JasperViewer(printReport, false);
            viewer.getContentPane().add(jv.getContentPane());
            viewer.setVisible(true);

        }catch(JRException ex){
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        
        }
            JOptionPane.showMessageDialog(rootPane, "Atestado Gerado com Sucesso!");

            AtestadoDAO dao = new AtestadoDAO();
            dao.remover(atestado);
            
            limpaCampos();
                             
    }//GEN-LAST:event_btGerarAtestadoActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        Date datasistema = new Date(); //a data do sistema é no tipo Date
        SimpleDateFormat formato = new SimpleDateFormat ("dd/MM/yyyy"); //instanciei um formato de data do sistema e alterei para uma label
        tfData.setText(formato.format(datasistema));
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(telaAtestados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(telaAtestados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(telaAtestados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(telaAtestados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new telaAtestados().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btGerarAtestado;
    private javax.swing.JButton btNovoDentista1;
    private javax.swing.JButton btNovoPaciente1;
    private javax.swing.JButton btPesquisarDentista1;
    private javax.swing.JButton btPesquisarPaciente1;
    private javax.swing.JButton btSair;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JFormattedTextField tfData;
    private javax.swing.JTextField tfDentista;
    private javax.swing.JTextField tfDiasdeAtestado;
    private javax.swing.JTextField tfPaciente;
    // End of variables declaration//GEN-END:variables
}
